package com.intelligent.eayon.utils;

import org.springframework.util.StringUtils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class IpUtils {
    /**
     * @param type net interface name
     * @return
     */
    public static String getLocalIp(String type) {
        String ipRes = "";
        try {
            Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                String netName = netInterface.getName();
                //System.out.println(netInterface.getName());
                Enumeration addresses = netInterface.getInetAddresses();
                int flag = 0;
                while (addresses.hasMoreElements()) {
                    ip = (InetAddress) addresses.nextElement();
                    if (ip != null && ip instanceof Inet4Address) {
                        if (netName.contains(type)) {
                            ipRes = ip.getHostAddress();
                            flag = 1;
                            break;
                        }
                    }
                }
                if (flag == 1) {
                    break;
                }

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return ipRes;
    }

    /**
     * isIP
     *
     * @param addr addr
     * @return boolean
     */
    public static boolean isIP(String addr) {
        if (!StringUtils.isEmpty(addr)) {
            String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
            if (addr.matches(regex)) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * isPort
     *
     * @param port port
     * @return boolean
     */
    public static boolean isPort(String port) {
        if (!StringUtils.isEmpty(port)) {
            if (port.matches("[0-9]+")) {
                int portInt = Integer.parseInt(port);
                if (portInt >= 0 && portInt <= 65535) {
                    return true;
                }
            } else {
                return false;
            }
        }
        return false;
    }
}
